package everyday;

/**
 * @author le
 */
public class Test02
{
    public static void main(String[] args)
    {
        System.out.println(characterReplacement("abbbdbbbd", 5));
    }

    public static int characterReplacement (String str, int k) {
        // write code here
        char[] array = str.toCharArray();
        if (k >= array.length){
            return array.length;
        }
        int begin = 0;
        int end = 0;
        int max = 0;

        int tmpBegin = 0;
        int tmpEnd = 0;
        for (int i = 0;i < array.length-1;i++){
            if (array[i] == array[i+1]){
                tmpEnd++;
            }else {
                if ((tmpEnd-tmpBegin) > max){
                    begin = tmpBegin;
                    end = tmpEnd;
                    max = tmpEnd - tmpBegin+1;
                }
                tmpBegin = i+1;
                tmpEnd = i+1;
            }
        }
        int index = begin;
        while(k > 0){
            if (array[index] != array[begin]){
                array[begin] = array[index];
                begin--;
                k--;
            }

            if (array[index] != array[end]){
                array[end] = array[index];
                end++;
                k--;
            }
        }
        return end-begin;

    }

}
